package cn.com.pc.content.support.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;


/**
 *
 * @author xhchen
 */
public class HtmlCMSUtils {
	private final static int SEP_COUNT = 9;
	private final static String SEPERATOR = "MROBOT_HR";

	private  static String WIDTH_PARAM = "";
	private  static String QUALITY_PARAM = "";

	public static String getWidthParam(){
		if(StringUtils.isBlank(WIDTH_PARAM))	{
			WIDTH_PARAM= "640";
		}
		return WIDTH_PARAM;
	}

	public static String getQualityParam(){
		if(StringUtils.isBlank(QUALITY_PARAM))	{
			QUALITY_PARAM= "30";
		}
		return QUALITY_PARAM;
	}
	private final static String REFRESH_IMG =
			"<img class=\"refresh\" alt=\"\" src=\"http://img2.pconline.com.cn/pconline/1102/28/2348980_shuaxin.jpg\" />";

	public static String filterRefreshImg(String html, String articleId, String prefix) {
		int pos = html.indexOf(REFRESH_IMG);
		if (pos == -1) {
			return html;
		}
		return html.replace(REFRESH_IMG,
				"<a href=\"javascript:void(888);\" onclick=\"refreshImg(event,'" + prefix + articleId + "?[time]&brower=inner')\" >"
						+ REFRESH_IMG + "</a>");
	}

	public static String replaceHttpUrl(String url) {
		if (url == null) return null;
		if (url.startsWith("//")) {
			url = "http:" + url ;
		} else if (url.startsWith("https://")) {
			url = url.replaceFirst("https", "http");
		}
		return url;
	}

	public static String changeRelateAet(String content, String type, Object... params){
		if(StringUtils.isBlank(content)){
			return "";
		}
		StringBuffer relateSb = new StringBuffer();
		relateSb.append("<div class=\"m-block\">");
		Pattern pBrief = Pattern.compile("(?i)<b\\s*brief=\"brief\"[^<^>]*?>(.*?)</b>");
		Matcher mBrief = pBrief.matcher(content);
		if(mBrief.find()){
			String brief = mBrief.group(1);
			if(!StringUtils.isBlank(brief)){
				relateSb.append("<strong class=\"u-title\">").append(brief.replaceAll("<[^<^>]*?>", "")).append("</strong>");
			}
		}else{
			relateSb.append("<strong class=\"u-title\">编辑推荐阅读</strong>");
		}
		relateSb.append("<div class=\"m-relaArts\" id=\"JrelaArts\">");
		relateSb.append("<div class=\"relaArtsWrap\">");
		//Pattern p = Pattern.compile("(?i)<p\\s*image=[\'\"](\\S*?)[\'\"]\\s*>\\s*(\\S*?)\\s*<br/>\\s*<a[^<^>]*?href=[\'\"](\\S*?)[\'\"][^<^>]*?>.*?</a>\\s*</p>");
		Pattern p = Pattern.compile("(?i)<p\\s*image=[\'\"](\\S*?)[\'\"]\\s*wap3g=[\'\"](\\S*?)[\'\"]\\s*>([\\s\\S]*?)</p>");
		Pattern p2 = Pattern.compile("(?i)(.*?)\\s*?<a[^<^>]*?href=[\'\"](\\S*?)[\'\"][^<^>]*?>");
		Matcher m = p.matcher(content);
		boolean isMrobot = "mrobot".equalsIgnoreCase(type);
		int matchNum = 0;
		try{
			while(m.find()){
				String imageUrl = m.group(1);
				String wap3g = m.group(2);
				String titleAndPcUrl = m.group(3);
				String title = null;
				String url = null;
				if(!StringUtils.isBlank(titleAndPcUrl)){
					Matcher m2 = p2.matcher(titleAndPcUrl.trim());
					if(m2.find()){
						title  = m2.group(1);
						if( ("<i class=\"u-icon-point\"></i>".equals(title) || "<i class=\"u-icon-point\">&nbsp;</i>".equals(title)) && isMrobot){
							Matcher mNew = Pattern.compile("(?i)(.*?)\\s*?<a[^<^>]*?href=[\'\"](\\S*?)[\'\"][^<^>]*?>(.*?)</a>").matcher(titleAndPcUrl.trim());
							if(mNew.find()){
								title = mNew.group(3);
							}
						}
						title = title != null ? title.replaceAll("<[^<^>]*?>", "") : "";
						url = m2.group(2);
						if(isMrobot){
							//relateSb.append("<a href=\"").append(changeToMrobotLink(url)).append("\">");
							String temurl = changeToMrobotLink(url);
							relateSb.append(temurl);
						}else{
							if(!StringUtils.isBlank(wap3g)){
								relateSb.append("<a href=\"").append(wap3g).append("\">");
							}else{
								relateSb.append("<a href=\"").append(url).append("\">");
							}
						}
						relateSb.append("<i class=\"u-pic\"><img src=\"").append(imageUrl).append("\"></i>");
						relateSb.append("<em>").append(title).append("</em>");
						relateSb.append("</a>");
						matchNum++;
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		relateSb.append("</div></div></div>");
		if(matchNum > 0){
			return relateSb.toString();
		}else{
			return content;
		}
	}

	public static String changeToMrobotLink(String href){
		if (!StringUtils.isBlank(href)) {
			href = href.trim();
			//把双斜杠和https替换为http进行判断,因为总出口还是会替换回来的，这里便于维持之前的逻辑判断
			href = replaceHttpUrl(href);
			if (href.startsWith("http://bbs.pcauto.com.cn")) { //跳往汽车网论坛
				Pattern pattern = Pattern.compile("^http:\\/\\/bbs.pcauto.com.cn\\/(topic|forum)-(\\d+)\\.html$");
				Matcher matcher = pattern.matcher(href);
				if (matcher.matches()) {
					if ("topic".endsWith(matcher.group(1))&&!StringUtils.isBlank(matcher.group(2))) {
						return "<a onclick='if(event)event.stopPropagation();' href='pcautobrowser://bbs-topic/" + matcher.group(2) + "'>";
					}
					if ("forum".endsWith(matcher.group(1))&&!StringUtils.isBlank(matcher.group(2))) {
						return "<a onclick='if(event)event.stopPropagation();' href='pcautobrowser://bbs-topics/" + matcher.group(2) + "'>";
					}
				}
			} else if (href.startsWith("http://price.pcauto.com.cn")) {//跳往汽车报价库
				String browser = getPcautoBrowser(href);
				if (!StringUtils.isBlank(browser)) {
					return "<a onclick='if(event)event.stopPropagation();' href='" + browser + "'>";
				}
			} else{//汽车网或电脑网的相关文章
				Pattern pcautoPattern = Pattern.compile("^http:\\/\\/(\\w+).(pcauto|pconline|pclady|pcbaby|pcgames).com.cn\\/.*?(\\d+)\\/(\\d+)(_\\d+|_all)?\\.html$");
				Matcher matcher = pcautoPattern.matcher(href);
				if(matcher.matches()){
					String pageNo = matcher.group(5);
					int pageNum = 0;
					if(!StringUtils.isBlank(pageNo) && pageNo.matches("_\\d+")){
						pageNum = NumberUtils.toInt(pageNo.substring(1));
						pageNo = "?pageNo=" + (pageNum + 1);
					}else{
						pageNo = "?pageNo=1";
					}
					return "<a  onclick='if(event)event.stopPropagation();' href='"+ matcher.group(2)
							+ "browser://information-article/" + matcher.group(4) + pageNo + "'>";
				}
			}
			href = "<a target=\"_blank\" href=\"" + href + (href.indexOf("?") != -1 ? "&" : "?") + "browser=commonWebView\" >";
		}
		return href;
	}

	public static  String getPcautoBrowser(String href) {
		String param = null;
		String serialId = null;
		String serialName = null;
		String modelName = null;
		String modelId = null;
		//把双斜杠和https替换为http进行判断,因为总出口还是会替换回来的，这里便于维持之前的逻辑判断
		href = replaceHttpUrl(href);
		String hrefWithOutParam = href;
		try {
			//若链接含有车型id,则通过车型id获取车系id、车系名称、车型名称
			Pattern pattern = Pattern.compile("\\/m(\\d*)|mid=(\\d*)");
			Matcher macher = pattern.matcher(href);
			if (macher.find()) {
				modelId = macher.group(1)!=null?macher.group(1):macher.group(2);
				String url = "http://price.pcauto.com.cn/price/api/v1/model/model_infos?mid="+ modelId;
				String txt = null;
				//报错屏蔽 TODO
				//txt = StringUtils.readHtml4Get(url, StringUtils.DEFAULT_PROXY_CONFIG);
				if (txt!=null)txt=txt.trim().replaceFirst("^\\(","").replaceAll("\\)$","");
				//报错屏蔽 TODO
           	/*Map rmap = StringUtils.jsontxt2Map(txt,StringUtils.DEFAULT_ENCODING,false);
           	modelName = (String)rmap.get("name");
           	serialId = (String)rmap.get("sgid");*/
				//报错屏蔽 TODO
           	/*Serial m=(Serial)EnvUtils.getEnvService().queryForObject("Serial","q_eq_serialId_i="+serialId);
           	if (m != null) {
           		serialName = m.getSerialGroupName();
           	} else {
           		url = "http://price.pcauto.com.cn/interface/common/serialGroup_info.jsp?sid="+ serialId;
       			txt = StringUtils.readHtml4Get(url, StringUtils.DEFAULT_PROXY_CONFIG);
               	if (txt!=null)txt=txt.trim().replaceFirst("^\\(","").replaceAll("\\)$","");
               	rmap = StringUtils.jsontxt2Map(txt,StringUtils.DEFAULT_ENCODING,false);
               	serialName = (String)rmap.get("sgName");
           	}*/
			}
			if (href.split("\\?").length > 1) {
				hrefWithOutParam = href.split("\\?")[0];
				param = href.split("\\?")[1];
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		StringBuilder sb = new StringBuilder("");
		Pattern pattern = Pattern.compile("^http:\\/\\/price.pcauto.com.cn\\/(m|sg|comment\\/sgz|comment\\/m|cars\\/sg)(\\d+)(\\/?)(.*)");
		Matcher macher = pattern.matcher(hrefWithOutParam);
		if (macher.matches()) {
			if (!StringUtils.isBlank(macher.group(1))&&!StringUtils.isBlank(macher.group(2))) {
				if ("m".equals(macher.group(1))&&StringUtils.isBlank(macher.group(4))){//车型页
					sb.append("pcautobrowser://").append("model/").append(macher.group(2) + "?serialId=" + serialId + "&serialName=" + serialName);
				}else if ("m".equals(macher.group(1))&&"price.html".equals(macher.group(4))){//了解经销商报价
					sb.append("pcautobrowser://").append("model/").append(macher.group(2) + "?serialId=" + serialId + "&serialName=" + serialName);
				}else if ("sg".equals(macher.group(1))&&StringUtils.isBlank(macher.group(4))){//车系页
					sb.append("pcautobrowser://").append("serial/").append(macher.group(2));
					//	 }else if("sg".equals(macher.group(1))&&"config.html".equals(macher.group(4))) {  //参数页
					//		 sb.append("pcautobrowser://").append("car-parameter/").append(macher.group(2));
				}else if("comment/sg".equals(macher.group(1))) {  //车主点评
					sb.append("pcautobrowser://").append("chezhudianping/").append(macher.group(2));
				}else if("comment/m".equals(macher.group(1))) {  //车主点评
					sb.append("pcautobrowser://").append("chezhudianping/").append(macher.group(2));
				}else if ("cars/sg".equals(macher.group(1))) {//图片页
					sb.append("pcautobrowser://").append("serial-Photo/").append(macher.group(2)).append("?param=serialGroupId");
				}else if ("cars/m".equals(macher.group(1))) {//图片页
					sb.append("pcautobrowser://").append("serial-Photo/").append(macher.group(2)).append("?param=serialGroupId");
				}
			}
		}
		Pattern pattern2 = Pattern.compile("^http:\\/\\/price.pcauto.com.cn\\/dealer\\/commorders\\/order\\.jsp\\?(.*)(sgid|mid)=(\\d+)(&)?(.*)");
		Matcher macher2 = pattern2.matcher(href);
		if (macher2.matches()) {
			if (!StringUtils.isBlank(macher2.group(2))&&!StringUtils.isBlank(macher2.group(3))) {
				//String modelId="";
				String image="";
				if("mid".equals(macher2.group(2))){
					//modelId=macher2.group(3);
				}else {
					return "pcautobrowser://auto-ask-price/?serialId="+macher2.group(3)+"&modelName=&dealerId=&dealerName=&image=";
				}
				if(href.indexOf("mname=")!=-1)
					modelName=href.replaceAll("(.*)mname=([^&]*)(&)?(.*)", "$2");
				if(href.indexOf("image=")!=-1)
					image=href.replaceAll("(.*)image=([^&]*)(&)?(.*)", "$2");
				sb = new StringBuilder("");
				sb.append("pcautobrowser://").append("auto-ask-price/?modelId=").append(modelId).append("&serialId=").append(serialId)
						.append("&modelName=").append(modelName).append("&dealerId=&dealerName=").append("&image=").append(image);
			}
		}
		return sb.toString();
	}

	public static String filterWapImg(String uri, int width) {
		if (uri == null) return null;
		//把双斜杠和https替换为http进行判断,因为总出口还是会替换回来的，这里便于维持之前的逻辑判断
		uri = replaceHttpUrl(uri);
		if (uri.startsWith("http://img0.") ||
				uri.startsWith("http://img1.") ||
				uri.startsWith("http://img2.") ||
				uri.startsWith("http://img3.")) {
			int pos = uri.indexOf('.');
			if (width == 150) {
				return uri.substring(0, pos) + 'm' + uri.substring(pos);
			}
			int pos2 = uri.indexOf('/', pos);
			return uri.substring(0, pos) + /*'m' +*/ uri.substring(pos, pos2) + /* '/' + width +*/ uri.substring(pos2);

		}

		if (uri.startsWith("http://img.") && uri.indexOf("/images/upload/upc/") > 0) {
			int pos = uri.indexOf('.');
			int pos2 = uri.lastIndexOf('.');
			if (width == 150) {
				return uri.substring(0, pos) + "rt" + uri.substring(pos, pos2) + "/spcgroup/width/150x150" + uri.substring(pos2);
			}
			return uri;
		}

		if (uri.startsWith("http://img.") && uri.indexOf("/images/pcautogallery/modle/article/") > 0) {
			int pos = uri.indexOf('.');
			int pos2 = uri.lastIndexOf('.');
			if (width == 150) {
				return uri.substring(0, pos) + "rt" + uri.substring(pos, pos2).replaceAll("(.*)\\.(pcgames|pconline|pclady|pcauto|pchouse|pcbaby)\\.(.*)", "$1.pconline.$3") + "/spcgroup/width/150x150" + uri.substring(pos2);
			}
			return uri;
		}

		if (uri.startsWith("http://imgup0.") ||
				uri.startsWith("http://imgup1.") ||
				uri.startsWith("http://imgup2.") ||
				uri.startsWith("http://imgup3.")) {
			int p2 = uri.indexOf(':', 10);
			int p3 = uri.indexOf("/vp20/");
			if (width == 150) {
				if (p2 != -1) {
					return uri.substring(0,10) + uri.charAt(12) + 'm' + uri.substring(13, p2) + uri.substring(p3 + 5);
				} else {
					return uri.substring(0,10) + uri.charAt(12) + 'm' + uri.substring(13);
				}
			}
			if (p2 != -1) {
				return uri.substring(0,10) + uri.charAt(12) + /*'m' +*/ uri.substring(13, p2) + /*'/' + width +*/ uri.substring(p3 + 5);
			} else {
				return uri.substring(0,10) + uri.charAt(12) + /*'m' +*/ uri.substring(13);

			}
		}
		return uri;
	}

	//拼接用户头像
	public static String face(long userId, String uri, String suffix){
		String id = String.valueOf(userId);
		long no = 1 ;
		if(uri!=null){
			uri = uri.replace("(?)", String.valueOf(no));
		}
		StringBuilder sb = new StringBuilder(uri+"/");
		for (int i = 0, c = id.length(); i < c; i += 2) {
			sb.append(id.charAt(i));
			if (i < c - 1) {
				sb.append(id.charAt(i + 1));
			}
			sb.append('/');
		}
		return sb.append(id).append("_").append(suffix).toString();
	}
}
